package com.scheduled.demo.config;

import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.net.UnknownHostException;


/**
 * @description:
 * @author: chenjianshuo
 * @create: 2019-09-04 16:38
 **/


public class RedisConfigFactory {


    public static JedisClientConfiguration poolConfig(int maxTotal, Long maxWaitMillis, int maxIdle, int minIdle) {
        JedisPoolConfig jjPoolConfig = new JedisPoolConfig();
        jjPoolConfig.setMaxTotal(maxTotal);
        jjPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jjPoolConfig.setMaxIdle(maxIdle);
        jjPoolConfig.setMinIdle(minIdle);
        return JedisClientConfiguration.builder().usePooling().poolConfig(jjPoolConfig).build();
    }


    public static JedisConnectionFactory jedisConnectionFactory(String hostName, Integer port, String password, Integer database, JedisClientConfiguration jedisClientConfiguration) {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(hostName);
        configuration.setPort(port);
        configuration.setPassword(password);
        configuration.setDatabase(database);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(configuration, jedisClientConfiguration);
        return jedisConnectionFactory;
    }

    public static StringRedisTemplate stringRedisTemplate(JedisConnectionFactory factory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        return template;
    }

    public static RedisTemplate<Object, Object> redisTemplate(JedisConnectionFactory factory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

}
